<template>
  <div>
    <!-- 头部 -->
    <a-form ref="searchRef" :model="searchForm" :hideRequiredMark="true" style="margin-bottom: 20px">
      <a-row>
        <a-form-item label="服务编号" name="ticketName">
          <a-input placeholder="" v-model:value="searchForm.serviceId" allow-clear maxlength="10"></a-input>
        </a-form-item>
        <a-form-item label="服务名称" name="ticketName">
          <a-input placeholder="" v-model:value="searchForm.serviceName" allow-clear maxlength="10"></a-input>
        </a-form-item>
        <a-form-item label="服务类型">
          <a-cascader
            v-model:value="valueList"
            :options="typeList"
            :load-data="loadData"
            change-on-select
            :field-names="{
              label: 'name',
              value: 'id'
            }"
          />
        </a-form-item>

        <a-col :span="4" :offset="1">
          <a-form-item name="saleValue" label="状态：">
            <a-select ref="select" v-model:value="searchForm.serviceStatus" @focus="focus" @change="handleChange" placeholder="请选择">
              <a-select-option v-for="item in buyCar2" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="2" :offset="1">
          <a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
        </a-col>
        <!-- <a-col :span="2">
          <a-button @click="reset">重置</a-button>
        </a-col> -->
      </a-row>
    </a-form>
    <!-- 左侧一级分类服务列表 这个要手写？这样位置有点奇怪啊感觉着可以再写一个table表格啊哈-->
    <div class="main">
      <!--右侧二级分类列表 -->
      <div style="flex: 1">
        <a-table
          :columns="childrenColums"
          :data-source="childrenList"
          bordered
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :scroll="{ y: 540, x: 'auto' }"
        >
          <template #updatedAt="{ record }">
            <div>
              {{ record.createdAt === record.updatedAt ? '' : record.updatedAt }}
            </div>
          </template>
          <template #status="{ record, index }">
            <div>{{ buyCar2[record.status].name }}</div>
          </template>
          <template #operation="{ record }">
            <a-button type="link" @click="editService(record, 0, 'look')" v-has="{ a: $route, b: 1 }">查看</a-button>
            <a-button type="link" v-if="record.status == 0" @click="editService(record, 0)" v-has="{ a: $route, b: 2 }">审核</a-button>
          </template>
        </a-table>
      </div>
    </div>
  </div>
  <div>
    <!-- 工作流程 -->
    <a-modal :visible="flowPop" :footer="null" width="50%" @cancel="closeFlowPop">
      <div class="flowWrap">
        <a-form ref="formRef" name="dynamic_form_nest_item" :model="dynamicValidateForm" @finish="onFinish">
          <div class="f_item">
            <div class="left"><span class="spot">*</span> 服务规范</div>
            <div class="right">
              <a-form-item
                :name="['serveName']"
                :rules="{
                  required: true,
                  message: '请输入服务规范'
                }"
              >
                <a-input v-model:value="dynamicValidateForm.serveName" placeholder="请输入服务规范"></a-input>
              </a-form-item>
            </div>
          </div>
          <div class="f_item">
            <div class="left"><span class="spot">*</span> 规范详情</div>
            <div class="right">
              <div class="flex" style="margin-left: -174px; margin-bottom: 10px">
                <div class="tip">示列：</div>
                <div class="flex">
                  <a-form-item>
                    <a-input :disabled="true" value="一、联系客户" />
                  </a-form-item>
                  <a-form-item style="margin-left: 22px">
                    <a-textarea
                      class="myhtml"
                      :disabled="true"
                      :auto-size="{ minRows: 4 }"
                      value="1.确认服务时间，地点\n 2.确认客户耗材准备情况\n 3.确认医嘱信息是否齐全"
                    ></a-textarea>
                  </a-form-item>
                </div>
              </div>
              <a-space v-for="(user, index) in dynamicValidateForm.users" :key="user.id">
                <div style="display: flex; align-items: center; margin-bottom: 8px; margin-left: 80px !important">
                  <!-- <div class="tip" style="opacity: 0; margin-left: 30px">
                    示列：
                  </div> -->
                  <a-form-item
                    :name="['users', index, 'first']"
                    :rules="{
                      required: true,
                      message: '请输入标题'
                    }"
                  >
                    <a-input v-model:value="user.first" placeholder="请输入标题" />
                  </a-form-item>
                  <a-form-item
                    style="margin-left: 16px"
                    :name="['users', index, 'last']"
                    :rules="{
                      required: true,
                      message: '请输入具体步骤。'
                    }"
                  >
                    <a-textarea
                      v-model:value="user.last"
                      :auto-size="{ minRows: 5 }"
                      placeholder="请输入具体步骤。如有多个步骤，请换行输入"
                    />
                  </a-form-item>
                  <!-- <MinusCircleOutlined
                    @click="removeUser(user)"
                  /> -->
                </div>
              </a-space>

              <a-form-item>
                <a-row style="margin-top: 20px">
                  <a-col :span="4" :offet="8" style="margin-left: 40%">
                    <a-button @click="closeFlowPop" class="d-a-center">关闭</a-button>
                  </a-col>
                </a-row>
              </a-form-item>
            </div>
          </div>
        </a-form>
      </div>
    </a-modal>
    <a-modal :visible="visible" :footer="null" width="90%" @cancel="cancel">
      <a-tabs v-model:activeKey="activeKey" class="user">
        <a-tab-pane key="0" :tab="headerTitle + '服务项目'" v-if="type == 0 || type == 2">
          <!-- 新增服务项 -->
          <a-form ref="modalRef" :rules="rules" :model="modalForm" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-item label="服务名称" name="name">
              <a-input placeholder="请输入服务名称" v-model:value="modalForm.name"></a-input>
            </a-form-item>
            <a-form-item label="服务类型" name="typeId">
              <a-input placeholder="请输入服务名称" v-model:value="modalForm.serviceKindName"></a-input>
            </a-form-item>
            <a-form-item label="服务排序" name="sort">
              <a-input placeholder="请输入大于0的服务排序数字" v-model:value="modalForm.sort" type="number"></a-input>
            </a-form-item>

            <a-form-item label="只为权益卡服务" name="isDown">
              <a-select ref="select" v-model:value="modalForm.isDown" @focus="focus" @change="handleMyChange" placeholder="请选择是或否">
                <a-select-option v-for="item in buyCar1" :value="item.id + ''" :key="item.id">{{ item.name }} </a-select-option>
              </a-select>
            </a-form-item>
            <!-- <a-select
                ref="select"
                v-model:value="modalForm.typeId"
                style="width: 150px"
                @focus="focus"
                @change="handleChange"
                placeholder="请选择服务类型"
              >
                <a-select-option
                  :value="item.id"
                  v-for="item in serviceList"
                  :key="item.id"
                  >{{ item.name }}</a-select-option
                >
              </a-select> -->
            <!-- </a-form-item> -->
            <a-form-item label="价格" name="price">
              <!-- <a-input
                style="width: 100px"
                v-model:value="modalForm.price"
              /> -->
              <a-input-number :min="0.01" max="9999" v-model:value="modalForm.price"></a-input-number>

              <span style="margin-left: 10px">元</span>
            </a-form-item>
            <a-form-item label="市场价格" name="mallPrice">
              <a-input-number :min="0.01" max="9999" v-model:value="modalForm.mallPrice"></a-input-number>

              <span style="margin-left: 10px">元</span>
            </a-form-item>
            <a-form-item label="时长" name="hours">
              <!-- <a-input
                v-model:value="modalForm.hours"
                style="width: 100px"
              /> -->
              <a-input-number :min="1" max="9999" v-model:value="modalForm.hours"></a-input-number>
              <span style="margin-left: 10px">分钟</span>
            </a-form-item>
            <a-form-item label="服务简介" name="introduction">
              <a-textarea placeholder="请输入服务简介" v-model:value="modalForm.introduction"></a-textarea>
            </a-form-item>
            <a-form-item label="佣金结算" name="serviceWindRatio">
              <a-input v-model:value="modalForm.serviceWindRatio" suffix="%"></a-input>
            </a-form-item>
            <a-form-item label="热门服务排序" name="popularSort">
              <a-input placeholder="请输入大于0的热门服务排序数字" v-model:value="modalForm.popularSort" type="number"></a-input>
            </a-form-item>
            <a-form-item label="热门服务封面" name="img">
              <a-upload
                v-model:file-list="popularImgUrlList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="popularImage"
                :before-upload="beforeUpload"
              >
                <div v-if="popularImgUrlList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="服务封面" name="img">
              <a-upload
                v-model:file-list="fileList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="uploadImage"
                :before-upload="beforeUpload"
                @change="handleChange1"
              >
                <div v-if="fileList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
              <!-- <upload-image
                :maxCount="9"
                v-model:fileList="fileList"
                ref="uploadRef"
                @change="uploadResult"
              ></upload-image> -->
            </a-form-item>
            <a-form-item label="服务内容图" name="img">
              <div v-if="imgList.length > 0">
                <img style="height: 50px; width: 50px" :src="item.url" v-for="(item, index) in imgList" :key="index" alt="" />
              </div>
            </a-form-item>
            <a-form-item label="产品介绍" name="img">
              <a-upload
                v-model:file-list="fileList2"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="uploadImage2"
                :before-upload="beforeUpload"
                @change="handleChange1"
              >
                <div v-if="fileList2.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>

            <!-- 新增 -->
            <a-form-item label="服务概述" name="img">
              <a-upload
                v-model:file-list="serviceOverviewList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="serviceUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="serviceOverviewList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="适用人群" name="img">
              <a-upload
                v-model:file-list="applicablePeopleList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="peopleUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="applicablePeopleList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="服务流程" name="img">
              <a-upload
                v-model:file-list="serviceProcessList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="processUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="serviceProcessList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="服务须知" name="img">
              <a-upload
                v-model:file-list="serviceInstructionsList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="instructionsUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="serviceInstructionsList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="费用须知" name="img">
              <a-upload
                v-model:file-list="feeNoticeList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="feeUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="feeNoticeList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>

            <a-form-item label="免责协议" name="img">
              <a-upload
                v-model:file-list="fileList3"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="uploadImage4"
                :before-upload="beforeUpload"
              >
                <!--  @change="handleChange1" -->
                <div v-if="fileList3.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="三级分类图标" name="img">
              <a-upload
                v-model:file-list="imgUrlList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="imgUrlUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="imgUrlList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="三级图标跳转链接" name="jumpLink">
              <a-input placeholder="请输入三级图标跳转链接" v-model:value="modalForm.jumpLink"></a-input>
            </a-form-item>
            <a-form-item label="服务告知书" name="serviceNotice">
              <a-textarea v-model:value="modalForm.serviceNotice" :auto-size="{ minRows: 3 }" placeholder="请输入服务告知书" />
            </a-form-item>
            <!-- <a-form-item label="服务详情" name="detail">
              <Tinymce
                :isText="true"
                ref="editor"
                :value="modalForm.detail"
                @input="tinymceInput"
                v-if="visible"
              ></Tinymce>
            </a-form-item>
            <a-form-item label="预约须知" name="notice">
              <Tinymce1
                ref="editor1"
                :isText="true"
                :value="modalForm.notice"
                @input="tinymceInput1"
                v-if="visible"
              ></Tinymce1>
            </a-form-item> -->
            <a-form-item label="服务详情">
              <div class="f_item">
                <div class="right">
                  <!-- <div class="flex" style="margin-left: -174px;margin-bottom: 10px;">
                <div class="tip">示列：</div>
                <div class="flex">
                  <a-form-item >
                    <a-input :disabled="true" value="服务标准" />
                  </a-form-item>
                  <a-form-item
                    style="margin-left: 22px"
                  >
                    <a-textarea
                      class="myhtml"
                      :disabled="true"
                      :auto-size="{ minRows: 4 }"
                      value="1.确认服务时间，地点\n 2.确认客户耗材准备情况"
                    ></a-textarea>
                  </a-form-item>
                </div>
              </div> -->
                  <!-- <a-form ref="serviceDetails"> -->
                  <a-space v-for="(service, index) in serviceDetails" :key="index">
                    <div style="display: flex; align-items: center; margin-bottom: 8px; margin-left: 50px !important">
                      <!-- <div class="tip" style="opacity: 0; margin-left: 30px">
                    示列：
                  </div> -->
                      <!-- <a-form-item
                   
                  > -->
                      <!--  :name="['users', index, 'serviceDetailTitle']"
                    :rules="{
                      required: true,
                      message: '请输入',
                    }" -->
                      <a-input v-model:value="service.serviceDetailTitle" placeholder="请输入标题" />
                      <!-- </a-form-item>
                  <a-form-item -->
                      <!-- style="margin-left: 16px" -->

                      <!-- > -->
                      <!--  :name="['users', index, 'serviceDetail']"
                    :rules="{
                      required: true,
                      message: '请输入具体步骤。',
                    }" -->
                      <a-textarea v-model:value="service.serviceDetail" :auto-size="{ minRows: 3 }" placeholder="请输入描述" />
                      <!-- </a-form-item> -->
                      <MinusCircleOutlined @click="removeService(index)" />
                    </div>
                  </a-space>

                  <!-- <a-form-item>
                <a-row style="margin-top: 20px">
                  <a-col :span="4" :offet="8" style="margin-left: 40%">
                    <a-button @click="closeFlowPop">关闭</a-button>
                  </a-col>
                  <a-col span="2" offet="8">
                    <a-button type="primary" html-type="submit">保存</a-button>
                  </a-col>
                </a-row>
              </a-form-item> -->
                  <!-- </a-form> -->
                </div>
              </div>
            </a-form-item>
            <a-form-item label="工作流程" name="reason">
              <!-- <a-textarea
                v-model:value="modalForm.reason"
                placeholder="请输入服务详情"
              /> -->
              <div class="flow">
                <table class="table">
                  <tr>
                    <th class="header" v-for="item in columnsFlow" :key="item.serveName">
                      {{ item.title }}
                    </th>
                  </tr>
                  <tr v-for="(tr, index) in dataFlow" :key="index">
                    <td v-for="(i, ind) in columnsFlow" :key="ind">
                      <div>{{ tr[i.dataIndex] }}</div>
                      <div v-if="i.dataIndex == 'operation'">
                        <a @click="handleEditFlow(tr, index)">查看</a>
                      </div>
                    </td>
                  </tr>
                </table>
              </div>
            </a-form-item>
            <a-form-item label="套餐列表" name="reason">
              <div>
                <table class="table">
                  <tr>
                    <th class="header" v-for="item in columns" :key="item.name">
                      {{ item.title }}
                    </th>
                  </tr>
                  <tr v-for="(tr, index) in dataSource" :key="index">
                    <template v-if="tr.isEdit" class="edit_class">
                      <td v-for="(i, ind) in columns" :key="ind">
                        <div v-if="ind == 3"></div>
                        <input v-else type="text" v-model="obj[i.dataIndex]" />
                      </td>
                    </template>
                    <template v-else>
                      <td v-for="(i, ind) in columns" :key="ind">
                        <div>{{ tr[i.dataIndex] }}</div>
                        <div v-if="i.dataIndex == 'operation'"></div>
                      </td>
                    </template>
                  </tr>
                </table>
              </div>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <!-- 新增服务类别 -->
        <a-tab-pane key="1" :tab="headerTitle + '服务类别'" force-render v-if="type == 1 || type == 2">
          <a-form ref="modalRef1" :model="modalForm1" :rules="rules1" :wrapper-col="{ span: 8 }" style="margin-top: 20px">
            <a-form-item :label="headerTitle + '服务类别'" name="name">
              <a-input placeholder="请输入服务类别" v-model:value="modalForm1.name"></a-input>
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
      <a-divider></a-divider>
      <!-- 确定和取消 -->
      <a-row justify="center" :gutter="10">
        <a-col :span="4">
          <div class="df">
            <a-button type="info" v-if="cancelText == '关闭'" @click="cancel" class="d-a-center">{{ cancelText }}</a-button>
            <a-button type="info" v-else @click="jujue" class="d-a-center">{{ cancelText }}</a-button>
          </div>
        </a-col>
        <a-col v-if="cancelText == '拒绝'" :span="4">
          <a-button type="primary" @click="tongguo()" class="d-a-center">通过</a-button>
        </a-col>
      </a-row>
    </a-modal>
    <!-- 拒绝原因 -->
    <a-modal :visible="storeVisible" @ok="associateStore" @cancel="storeVisible = false" okText="确定">
      <a-form ref="storeFormRef" :rules="rules1">
        <a-form-item label="拒绝原因" name="consumableLists">
          <a-input v-model:value="denyCause" placeholder=""></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import { reactive, ref, watch, computed, defineComponent, createVNode, toRefs } from 'vue'
import { useModal } from '@/hooks'
import { FormInstance } from 'ant-design-vue'
import {
  CheckOutlined,
  EditOutlined,
  ArrowDownOutlined,
  ArrowUpOutlined,
  ExclamationCircleOutlined,
  EditTwoTone,
  DeleteTwoTone,
  PlusOutlined,
  MinusCircleOutlined,
  LoadingOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons-vue'
import { Modal, message, notification } from 'ant-design-vue'
import Tinymce from '@/components/common/tinymce/tinymce'
import Tinymce1 from '@/components/common/tinymce/tinymce1'
import {
  selectAllType,
  selectAllService,
  updateAndAddService,
  updateOrAddType,
  deleteService,
  deleteType,
  selectServiceInfo,
  uploadPicture,
  servicesAuditList,
  serviceAudit,
  queryserviceTypeParent
} from '@/api/service/index.js'
import { buyCar2 } from '@/utils/dict.js'
import UploadImage from '@/components/common/UploadImage.vue'
export default {
  setup() {
    const serviceAct = ref(0)
    const data = reactive({
      hasSamePrice: true,
      typeList: [],
      valueList: [],
      serviceList: [],
      childrenList: [],
      loading: true, //表格加载
      // headerTitle: "",
      isEdit: '', //编辑or新增
      type: 2, //类型
      visible: false,
      activeKey: '0',
      uploadLoading: false,
      imageUrl: '',
      modalForm1: {},
      modalForm: {
        detail: ''
      },
      value: '',
      fileList: [],
      imgList: [],
      fileList2: [],
      fileList3: [],
      imgUrlList: [], //三级分类图标
      feeNoticeList: [], //费用须知
      serviceInstructionsList: [], //服务须知
      serviceProcessList: [], //服务流程
      applicablePeopleList: [], //适用人群
      serviceOverviewList: [], //服务概述
      popularImgUrlList: [],
      detail: '哈哈哈',
      uploadRef: '',
      cancelText: '拒绝',
      storeVisible: false,
      denyCause: '',
      searchForm: {},
      buyCar2,
      buyCar1: [
        {
          name: '是',
          id: 1
        },
        {
          name: '否',
          id: 0
        }
      ],
      columns: [
        {
          title: '套餐名称',
          dataIndex: 'sonServiceName',
          width: '30%'
        },
        {
          title: '套餐价格(元)',
          dataIndex: 'price'
        },
        {
          title: '套餐时长(分钟)',
          dataIndex: 'duration'
        },
        {
          title: '市场价格',
          dataIndex: 'mallPrice'
        },
        {
          title: '佣金结算比例',
          dataIndex: 'commissionSettlementRatio'
        },
        {
          title: '佣金结算金额',
          dataIndex: 'commissionSettlementAmount'
        },
        {
          title: '操作',
          dataIndex: 'operation'
        }
      ],
      flowPop: false,
      columnsFlow: [
        {
          title: '服务规范',
          dataIndex: 'serveName',
          width: '70%'
        },
        {
          title: '操作',
          dataIndex: 'operation'
        }
      ],
      // 工作流程数据
      dataFlow: [
        // {
        //  id:0
        //   name: "服务流程",
        //   operation: "",
        // },
      ],
      dataSource: [],
      obj: {},
      // 修改当前套餐的index
      flag: -1,
      serviceDetails: []
    })
    const modalRef = ref('')
    const modalRef1 = ref('')
    const editor = ref('')
    const editor1 = ref('')

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 5,
      total: 0
    })

    // 左侧服务分类列表
    const serviceColums = [
      {
        title: '服务名称',
        dataIndex: 'name',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'service'
        }
      }
    ]

    const childrenColums = [
      {
        title: '服务编号',
        dataIndex: 'id',
        className: 'table'
      },
      {
        title: '服务名称',
        dataIndex: 'name',
        className: 'table'
      },
      {
        title: '服务类型',
        dataIndex: 'servicesTypesName',
        className: 'table'
      },
      {
        title: '服务价格',
        dataIndex: 'price',
        className: 'table'
      },
      {
        title: '服务时长',
        dataIndex: 'hours',
        className: 'table'
      },
      {
        title: '服务概括',
        dataIndex: 'introduction',
        className: 'table'
      },
      {
        title: '提交审核时间',
        dataIndex: 'createdAt',
        className: 'table'
      },
      {
        title: '审核时间',
        dataIndex: 'updatedAt',
        className: 'table',
        slots: {
          customRender: 'updatedAt'
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        className: 'table',
        slots: {
          customRender: 'status'
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        slots: {
          customRender: 'operation'
        }
      }
    ]

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))
    initFirstService()
    async function initFirstService() {
      queryserviceTypeParent().then(r => {
        r.object.map(m => (m.name = m.kindName))
        r.object.map(el => (el.isLeaf = false))
        data.typeList = [...r.object]
      })
    }
    const loadData = async selectedOptions => {
      console.log('点击了选择----------------', selectedOptions)
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true // load options lazily
      let obj = {
        parentId: targetOption.id
      }
      let res = await selectAllType(obj)
      if (res.success) {
        // res.object.records.map((el) => (el.name = el.serveName));
        targetOption.children = res.object
        data.typeList = [...data.typeList]
      }
    }
    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      // console.log(pagination, "当前分页");
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      initChildrenList()
    }
    // 新增服务
    const addService = () => {
      data.fileList = []
      data.fileList2 = []
      data.fileList3 = []
      data.visible = true
      data.serviceDetails = []
      data.isEdit = 2
      data.type = 2
      data.activeKey = '0'
    }
    // 编辑服务和服务项目
    const editService = async (item, type, t) => {
      data.type = type
      data.isEdit = 1
      data.activeKey = String(type) //激活类型是

      if (type == 1) {
        data.modalForm1 = {
          name: item.name,
          id: item.id
        }
        data.visible = true
      } else {
        if (t == 'look') {
          // 查看
          data.cancelText = '关闭'
        } else {
          data.cancelText = '拒绝'
        }
        let res = await initServiceDetail(item.id)
        console.log(res.price)
        let price = res.price

        let sonPrice = res.sonServicesList.map(el => (el.key = el.price))
        console.log(price, sonPrice)
        let hasSamePrice = sonPrice.some(item => item === price)
        data.hasSamePrice = hasSamePrice
        console.log(hasSamePrice) // 如果为 true 则表示有相同的价格，否则为 false
        // if(res.price)
        if (res.isDown == 0) {
          res.isDown = '否'
        } else {
          res.isDown = '是'
        }
        res.typeId = String(res.typeId) //服务ID是string类型的
        data.modalForm = res
        data.imgList = res.contentPicture
          ? res.contentPicture.split(',').map(m => {
              return {
                url: m
              }
            })
          : []
        data.serviceDetails = [...(res.serviceDetails || [])]
        data.fileList = res.coverJson ? [{ url: res.coverJson }] : []
        data.fileList2 = res.productIntroduce ? [{ url: res.productIntroduce }] : []
        data.fileList3 = res.disclaimer
          ? [
              {
                url: res.disclaimer
              }
            ]
          : []
        data.imgUrlList = res.imgUrl ? [{ url: res.imgUrl }] : []

        data.feeNoticeList = res.feeNotice ? [{ url: res.feeNotice }] : [] //费用须知
        data.serviceInstructionsList = res.serviceInstructions ? [{ url: res.serviceInstructions }] : [] //服务须知
        data.serviceProcessList = res.serviceProcess ? [{ url: res.serviceProcess }] : [] //服务流程
        data.applicablePeopleList = res.applicablePeople ? [{ url: res.applicablePeople }] : [] //适用人群
        data.serviceOverviewList = res.serviceOverview ? [{ url: res.serviceOverview }] : [] //服务概述
        data.popularImgUrlList = res.popularImgUrl ? [{ url: res.popularImgUrl }] : []
        if (res.workFlow) {
          data.dataFlow = [...JSON.parse(res.workFlow || '')]
        }
        data.dataSource = [...res.sonServicesList]
        let priceList = res.sonServicesList.sort(function (a, b) {
          return a.price - b.price
        })
        data.dataSource = priceList
        // data.value = data.serviceList.find(
        //   (el) => el.id == String(res.typeId)
        // ).name;
        // console.log(data.value, "服务类型是");
        // 放在最后，要不然富文本无法渲染
        data.visible = true
      }
    }
    async function initServiceDetail(id) {
      let res = await selectServiceInfo(id)
      if (res.success) {
        return res.object
      }
    }

    // 获取服务下的子列表:本来写的一级和二级联动，嗯……然后呢？不动了……我……无语了……
    const getChildrenList = (e, index) => {
      if (serviceAct.value == index) return
      serviceAct.value = index
      page.current = 1
      initChildrenList()
    }

    const headerTitle = computed(() => {
      let title = data.isEdit == 1 ? '编辑' : '新增'
      return title
    })
    const rules = {
      name: [
        {
          required: true,
          message: '请输入内容标题!',
          trigger: 'change'
        },
        {
          min: 0,
          max: 20,
          message: '文字超出限制范围!',
          trigger: 'blur'
        }
      ],
      typeId: [
        {
          required: true,
          message: '请选择服务类型'
        }
      ],
      sort: [
        {
          required: true,
          message: '请输入大于0的服务排序数字!'
        }
      ],
      isDown: [
        {
          required: true,
          message: '请选择是否只为权益卡服务'
        }
      ],
      introduction: [
        {
          required: true,
          message: '请输入服务简介',
          trigger: 'blur'
        }
      ],
      notice: [
        {
          required: true,
          message: '请输入预约须知',
          trigger: 'blur'
        }
      ],
      detail: [
        {
          required: true,
          message: '请输入服务详情',
          trigger: 'blur'
        }
      ],
      price: [
        {
          required: true,
          message: '请输入服务价格'
        }
      ],
      hours: [
        {
          required: true,
          message: '请输入服务时长'
        }
      ]
    }
    const rules1 = {
      name: [
        {
          required: true,
          message: '请输入服务类别!',
          trigger: 'blur'
        }
      ]
    }
    const cancel = () => {
      console.log('点击了关闭')
      //置空
      data.modalForm1 = {}
      data.modalForm = {}
      data.dataSource = []
      data.dataFlow = []
      data.visible = false
    }
    //三级分类
    const imgUrlUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.imgUrlList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    const uploadImage2 = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      /*
				   直接打印formData是空的，别人说要通过get才能访问到
				    console.log(formData.get("file"), "上传图片");

				   formData上传的时候不能使用{}包括比如  let data={file:formData,name:'test'}
				    这样上传就是空对象……
				    let res = await uploadPicture(data);

				   只能单独放，这样才可以、和后端说下改下……
				   let res = await uploadPicture(formData);
				
				*/

      let res = await uploadPicture(formData, 'service')
      // // url存入列表中,为什么是两个fileList
      if (res.success) {
        // console.log(data.fileList, "fileList列表是");
        data.fileList2 = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
        // data.fileList.shift(1);
      }
      // console.log(data.fileList, "fileList列表是");
    }
    //服务概述
    const serviceUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.serviceOverviewList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    const popularImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.popularImgUrlList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //适用人群
    const peopleUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.applicablePeopleList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //服务流程
    const processUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.serviceProcessList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //服务须知
    const instructionsUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.serviceInstructionsList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //费用须知
    const feeUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.feeNoticeList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    const uploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      /*
				   直接打印formData是空的，别人说要通过get才能访问到
				    console.log(formData.get("file"), "上传图片");

				   formData上传的时候不能使用{}包括比如  let data={file:formData,name:'test'}
				    这样上传就是空对象……
				    let res = await uploadPicture(data);

				   只能单独放，这样才可以、和后端说下改下……
				   let res = await uploadPicture(formData);
				
				*/

      let res = await uploadPicture(formData, 'service')
      // // url存入列表中,为什么是两个fileList
      if (res.success) {
        data.fileList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }

    const handleChange = value => {
      data.modalForm.typeId = value
    }
    const previewVisible = ref(false)
    const previewImage = ref('')
    const imageUrl = ref('')

    function getBase64(img, callback) {
      const reader = new FileReader()
      reader.addEventListener('load', () => callback(reader.result))
      reader.readAsDataURL(img)
    }
    const handleCancel = () => {
      previewVisible.value = false
    }

    const handlePreview = async file => {
      // console.log(file, "上传图片这是");
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      previewImage.value = file.url || file.preview
      previewVisible.value = true
    }

    const handleChange1 = info => {
      if (info.file.status === 'uploading') {
        data.uploadLoading = true
        return
      }

      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, base64Url => {
          data.imageUrl = base64Url
          data.uploadLoading = false
        })
      }

      if (info.file.status === 'error') {
        data.uploadLoading = false
        message.error('上传错误')
      }
    }

    const beforeUpload = file => {
      const isJpgOrPng =
        file.type === 'image/psd' ||
        file.type === 'image/bmp' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/jpeg'

      if (!isJpgOrPng) {
        message.error('图片格式不正确!')
      }
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isLt2M) {
        message.error('图片大小不超过5MB!')
      }
      return isJpgOrPng && isLt2M
    }

    // 富文本内容
    const tinymceInput = value => {
      console.log(value, '服务简介')
      data.modalForm.detail = value
    }
    const tinymceInput1 = value => {
      // console.log(value, "预约须知");
      data.modalForm.notice = value
    }

    // 保存,根据tab的绑定的key值判断编辑服务项目还是类别
    const save = () => {
      console.log(data.modalForm, 'data.modalForm')

      let ref = data.activeKey == '0' ? modalRef : modalRef1

      ref.value
        .validate()
        .then(async () => {
          // console.log(data.modalForm, "表单内容");

          if (data.activeKey == '0') {
            if (data.fileList.length == 0) {
              message.error('请上传服务封面')
              return
            }
            // if (data.fileList2.length == 0) {
            //   message.error("请上传产品介绍");
            //   return;
            // }
            data.modalForm.coverJson = data.fileList[0].url
            data.modalForm.productIntroduce = data.fileList2[0].url
            data.modalForm.contentJson = data.fileList[0].url
            // data.modalForm.coverJson = '1111'
            // data.modalForm.contentJson = '222';
          }
          let f1 = false
          // 服务详情
          data.serviceDetails.map(s => {
            if (!s.serviceDetail || !s.serviceDetailTitle) {
              f1 = true
              return
            }
          })
          if (f1) {
            message.error('服务详情请输入完整！')
            return
          }
          data.modalForm.serviceDetails = [...data.serviceDetails]

          // 工作流程和
          // data.modalForm.workFlow = [...data.dataFlow];
          data.modalForm.workFlow = JSON.stringify(data.dataFlow)
          // 套餐列表
          let flag = false
          data.dataSource.map(m => {
            if (!m.sonServiceName || !m.price || !m.duration) {
              flag = true
            }
          })
          if (flag) {
            message.error('请保存套餐列表')
            return
          }
          if (data.isEdit == 1) {
            data.dataSource = data.dataSource.map(d => {
              d.serviceId = data.modalForm.id
              return d
            })
            data.modalForm.sonServicesList = [...data.dataSource]
          } else {
            data.modalForm.sonServicesList = [...data.dataSource]
          }
          if (data.activeKey == '0') {
            if (data.isEdit == 1) {
              // 编辑服务类别
              console.log('编辑服务')
              let res = await updateAndAddService(data.modalForm)
              if (res.success) {
                message.success('执行成功')
                data.visible = false
                data.dataSource = []
                data.dataFlow = []
                data.modalForm = {}
                initChildrenList()
              }
            } else {
              console.log('新增服务')
              let res = await updateAndAddService(data.modalForm)
              if (res.success) {
                message.success('执行成功')
                data.visible = false
                data.modalForm = {}
                initChildrenList()
              }
            }
          } else {
            let res = await updateOrAddType(data.modalForm1)
            if (res.success) {
              message.success('执行成功')
              data.visible = false
              data.modalForm1 = {}
              initServiceList()
            }
          }
          // 关闭弹窗
          // emit('closeModal')
        })
        .catch(error => {
          console.log('error', error)
        })
    }

    initServiceList()
    // 初始化服务列表
    async function initServiceList() {
      let obj = {
        pageNum: 1,
        pageSize: 100
      }
      let res = await selectAllType(obj)
      if (res.success) {
        res.object.map(el => (el.key = el.id))
        data.serviceList = res.object
        // res.object.records[0].id)
        initChildrenList()
      }
    }
    // 二级列表
    async function initChildrenList() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        // typeId: data.serviceList[serviceAct.value].id,
        ...data.searchForm
      }
      let res = await servicesAuditList(obj)
      if (res.success) {
        // res.object.list.map((el) => (el.key = el.id));
        data.childrenList = res.object.list
        page.total = res.object.total
        data.loading = false
      }
    }
    const closeFlowPop = () => {
      data.flowPop = false
      formRef.value.resetFields()
      dynamicValidateForm.serveName = ''
      dynamicValidateForm.users = []
      dynamicValidateForm.id = []
      dynamicValidateForm.isEdit = false
    }

    const methods = {
      handleFlowPop() {
        data.flowPop = true
      },
      handleAdd() {
        let idEdit = data.dataSource.some(i => i.isEdit)
        if (idEdit) return
        const newData = {
          key: ``,
          sonServiceName: ``,
          price: '',
          duration: ``,
          operation: '',
          isEdit: true
        }
        data.dataSource.push(newData)
      },
      handleEdit(ind) {
        data.flag = ind
        // data.dataSource = data.dataSource.map(i => i.isEdit=false)
        data.dataSource[ind].isEdit = true
        data.obj = {
          ...data.dataSource[ind],
          isEdit: true
        }
      },
      handleDelete(ind) {
        data.dataSource.splice(ind, 1)
      },
      handleDeleteDataFlow(i) {
        data.dataFlow.splice(i, 1)
      },

      handleSave() {
        console.log(data.obj, '======')
        if (!(data.obj && data.obj.sonServiceName && data.obj.price && data.obj.duration)) {
          message.error('请输入名称、价格、时长')
          return
        }
        if (data.flag > -1) {
          data.dataSource[data.flag] = {
            sonServiceName: data.obj.sonServiceName,
            price: data.obj.price,
            duration: data.obj.duration,
            operation: ''
          }
          data.flag = -1
        } else {
          data.dataSource.pop()
          data.dataSource.push({
            sonServiceName: data.obj.sonServiceName,
            price: data.obj.price,
            duration: data.obj.duration,
            operation: ''
          })
        }

        data.obj = {}
      }
    }
    // 工作流程
    const formRef = ref()
    const dynamicValidateForm = reactive({
      serveName: '',
      users: [],
      id: Date.now()
    })
    const handleEditFlow = (item, index) => {
      debugger
      console.log(data.dataFlow[index], '00000000')
      dynamicValidateForm.isEdit = true
      dynamicValidateForm.serveName = item.serveName
      dynamicValidateForm.id = item.id
      dynamicValidateForm.users = JSON.parse(item.users)

      data.flowPop = true
    }
    const removeService = index => {
      // let index = data.serviceDetail.indexOf(item);
      // if (index !== -1) {
      data.serviceDetails.splice(index, 1)
    }
    const removeUser = item => {
      let index = dynamicValidateForm.users.indexOf(item)
      // if (index !== -1) {
      dynamicValidateForm.users.splice(index, 1)
      // }
    }
    const addServiceDetail = () => {
      console.log(data.serviceDetails, 'res.serviceDetailsres.serviceDetails-----')

      data.serviceDetails.push({
        serviceDetailTitle: '',
        serviceDetail: ''
      })
    }
    const addUser = () => {
      dynamicValidateForm.users.push({
        first: '',
        last: '',
        id: Date.now()
      })
      console.log(dynamicValidateForm.users, '-------')
    }
    const onFinish = values => {
      if (dynamicValidateForm.users.length == 0) {
        message.error('请至少输入一条规范详情')
        return
      }
      debugger
      if (dynamicValidateForm.isEdit) {
        data.dataFlow = data.dataFlow.map(d => {
          if (d.id == dynamicValidateForm.id) {
            return {
              id: dynamicValidateForm.id,
              serveName: dynamicValidateForm.serveName,
              users: JSON.stringify(dynamicValidateForm.users)
            }
          }
          return d
        })
      } else {
        data.dataFlow.push({
          id: dynamicValidateForm.id,
          serveName: dynamicValidateForm.serveName,
          users: JSON.stringify(dynamicValidateForm.users)
        })
      }
      console.log('Received values of form:', {
        ...dynamicValidateForm
      })
      console.log('dynamicValidateForm.users:', dynamicValidateForm)
      closeFlowPop()
    }
    const jujue = () => {
      data.storeVisible = true
    }
    const tongguo = () => {
      if (!data.hasSamePrice) {
        message.error('价格与套餐列表价格不一致')
      }
      const { closeModal } = useModal.confirm({
        title: () => '确认通过此服务上架审核吗?',
        icon: () => createVNode(QuestionCircleOutlined),
        onOk: async () => {
          let res = await serviceAudit({
            id: data.modalForm.id,
            auditType: 1
          })
          if (res.success) {
            data.visible = false
            message.success('操作成功')
            initChildrenList()
            closeModal()
          }
        },

        class: 'test'
      })
    }
    const associateStore = async () => {
      if (!data.denyCause) {
        message.error('请输入原因')
        return
      }
      data.storeVisible = false
      let res = await serviceAudit({
        id: data.modalForm.id,
        auditType: 2,
        auditReason: data.denyCause
      })
      if (res.success) {
        message.success('操作成功')
        data.visible = false
        initChildrenList()
      }
    }
    const search = () => {
      page.current = 1
      if (data.valueList.length > 1) {
        data.searchForm.serviceTypeId = data.valueList[1]
      } else {
        delete data.searchForm.serviceTypeId
      }
      initChildrenList()
    }

    return {
      formRef,
      dynamicValidateForm,
      onFinish,
      removeUser,
      addUser,
      ...toRefs(data),
      ...methods,
      childrenColums,
      pagination,
      serviceAct,
      serviceColums,
      addService,
      editService,
      getChildrenList,
      handleTableChange,

      modalRef,
      imageUrl,
      labelCol: {
        style: {
          width: '150px',
          fontWeight: 'bold'
        }
      },
      wrapperCol: {
        span: 12
      },
      previewVisible,
      previewImage,
      rules,
      modalRef1,
      rules1,
      tinymceInput1,
      tinymceInput,
      handleCancel,
      handlePreview,
      handleChange,
      handleChange1,
      beforeUpload,
      save,
      cancel,
      headerTitle,
      uploadImage,
      uploadImage2,
      editor,
      editor1,
      closeFlowPop,
      handleEditFlow,
      addServiceDetail,
      removeService,
      jujue,
      associateStore,
      tongguo,
      search,
      loadData,
      serviceUploadImage,
      peopleUploadImage,
      processUploadImage,
      instructionsUploadImage,
      feeUploadImage,
      imgUrlUploadImage,
      popularImage
    }
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    EditTwoTone,
    DeleteTwoTone,
    ArrowUpOutlined,
    ArrowDownOutlined,
    PlusOutlined,
    LoadingOutlined,
    Tinymce,
    Tinymce1,
    UploadImage,
    MinusCircleOutlined,
    QuestionCircleOutlined
  }
}
</script>

<style scoped lang="less">
.flex {
  display: flex;
  align-items: center;
}

.main {
  display: flex;
  margin-top: 30px;
}

.ant-upload-text {
  padding: 40px;
  display: flex;
}

.service {
  display: flex;
  justify-content: space-between;

  // 服务激活样式
  .name-act {
    color: #2a9d8f;
    font-weight: bolder;
  }

  .edit {
    padding: 0px 5px;
  }
}

.process {
  display: flex;

  .process-list {
    margin-right: 20px;
    display: flex;
    flex-direction: column;

    .num {
      width: 50px;
      height: 50px;
      border: solid 1px #999;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
    }

    .img {
      width: 50px;
      height: 50px;
      background-color: tomato;
      margin: 10px 0px;
    }

    .title {
    }
  }
}

.table {
  width: 100%;
  border-left: 1px solid #eee;
  border-top: 1px solid #eee;

  tr {
    td {
      input {
        border: 1px solid #aaa !important;
        width: 97% !important;
      }
    }

    th,
    td {
      text-align: center;
      border-right: 1px solid #eee;
      border-bottom: 1px solid #eee;
    }
  }
}

.myhtml {
  width: 160%;
  height: 140%;
  padding: 8rpx 6rpx;
  border: 2rpx solid #d9d9d9;
  border-radius: 2px;
  color: rgba(0, 0, 0, 0.25);
  background: #f5f5f5;
}

.flowWrap {
  .f_item {
    padding: 20px 0 !important;
  }

  .left {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 22px;
    margin-right: 30px;

    .spot {
      color: red;
    }
  }
}

.ant-form-item {
  margin-bottom: 0px;
}
</style>
